package com.kexio.websocket.config;

import com.kexio.websocket.handler.WebSocketHandler;
import com.kexio.websocket.interceptor.WebSocketAuthInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

/**
 * WebSocket 配置类
 * 
 * 配置 WebSocket 端点和拦截器，支持实时通信功能。
 * 
 * @author Kexio Team
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    private static final Logger log = LoggerFactory.getLogger(WebSocketConfig.class);

    @Autowired
    private WebSocketHandler webSocketHandler;
    
    @Autowired
    private WebSocketAuthInterceptor authInterceptor;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        log.info("========================================");
        log.info("📡 开始注册 WebSocket 端点...");
        
        // 注册 WebSocket 处理器
        registry.addHandler(webSocketHandler, "/ws")
                .addInterceptors(authInterceptor)
                .setAllowedOrigins("*"); // 生产环境需要配置具体域名
        
        log.info("✅ WebSocket 端点已注册: /ws (实际路径: /api/ws)");
        log.info("🔒 已添加认证拦截器: WebSocketAuthInterceptor");
        log.info("🌐 允许的来源: * (开发环境)");
        
        // SockJS 兼容性支持
        registry.addHandler(webSocketHandler, "/sockjs")
                .addInterceptors(authInterceptor)
                .setAllowedOrigins("*")
                .withSockJS();
        
        log.info("✅ SockJS 端点已注册: /sockjs (实际路径: /api/sockjs)");
        log.info("========================================");
    }
}
